package com.netease.financial.module.authentication;

import android.text.TextUtils;

import com.netease.financial.domain.interactor.DefaultSubscriber;
import com.netease.financial.domain.interactor.UseCase;
import com.netease.financial.domain.model.Login;
import com.netease.financial.internal.di.ActivityScope;
import com.netease.financial.mapper.NfsViewModelDataMapper;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by hzwuyufeng on 1/20/16.
 */
@ActivityScope
public class AuthenticationPresenterImpl implements AuthenticationPresenter {

    private static final String TAG = AuthenticationPresenterImpl.class.getSimpleName();

    private AuthenticationView authenticationView;

    private final UseCase loginUseCase;
    private final NfsViewModelDataMapper nfsViewModelDataMapper;

    @Inject
    public AuthenticationPresenterImpl(@Named("login") UseCase loginUseCase, NfsViewModelDataMapper nfsViewModelDataMapper) {
        this.loginUseCase = loginUseCase;
        this.nfsViewModelDataMapper = nfsViewModelDataMapper;
    }

    @Override
    public void setView(AuthenticationView view) {
        this.authenticationView = view;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {
        loginUseCase.unsubscribe();
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void initialize() {
        login();
    }

    private void login() {
        authenticationView.showLoading();
        this.loginUseCase.execute(new LoginSubscriber());
    }

    private void handleLoginResult(Login login) {
        authenticationView.hideLoading();
        if (!TextUtils.isEmpty(login.getAccessToken())) {
            authenticationView.onSuccess();
        } else {
            handleLoginFailedEvent();
        }
    }

    private void handleLoginFailedEvent() {
        authenticationView.hideLoading();
        authenticationView.onError("验证失败，请确认密码输入正确，稍后再试");
    }

    private final class LoginSubscriber extends DefaultSubscriber<Login> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            AuthenticationPresenterImpl.this.handleLoginFailedEvent();
        }

        @Override
        public void onNext(Login login) {
            AuthenticationPresenterImpl.this.handleLoginResult(login);
        }
    }
}
